import Axios from 'axios'
import { LoadingBar, Message } from 'view-design'

const pathApi = '/api'

Axios.defaults.timeout = 10000
Axios.defaults.headers['Content-type'] = 'application/json;charset=UTF-8'

Axios.interceptors.request.use(
  config => {
    config.headers.common['web-token'] = sessionStorage.getItem('web-token') ? sessionStorage.getItem('web-token') : ''
    LoadingBar.start()
    return config
  },
  error => {
    return error
  }
)

Axios.interceptors.response.use(
  response => {
    if(response.headers['web-token']) {
      sessionStorage.setItem('web-token', response.headers['web-token'])
    }
    LoadingBar.finish()
    return response
  },
  error => {
    LoadingBar.error()
    // zuul层定义http响应码401为token为空，这里统一判断code，并返回msg
    if(parseInt(error.response.status) === 401) {
      Message.warning('token为空，请推出重新登录!')
      sessionStorage.setItem('web-token', '')
      sessionStorage.setItem('userInfo', '')
      window.location.href = '/#/login'
    }

    if(parseInt(error.response.status) === 402) {
      Message.warning('token已过期，请退出重新登录!')
      sessionStorage.setItem('web-token', '')
      sessionStorage.setItem('userInfo', '')
      window.location.href = '/#/login'
    }
    // 各种状态码的判断

    return error
  }
)

/**
 * get方法重写
 * */
Axios.GET = (url, params) => {
  return new Promise((resolve, reject) => {
    Axios.get(pathApi + url, {
      params
    }).then(res => {
      resolve(res.data)
    }).catch(err => {
      reject(err)
    })
  })
}

/**
 * post方法重写
 * */
Axios.POST = (url, params) => {
  return new Promise((resolve, reject) => {
    Axios.post(pathApi + url, JSON.stringify(params)).then(res => {
      resolve(res.data)
    }).catch(err => {
      reject(err)
    })
  })
}

export default Axios
